package config

import (
	"fmt"
	"log"
	"strings"

	"gitee.com/eeppee_admin/go-tuiftp/reuse"

	"github.com/charmbracelet/bubbles/cursor"
	"github.com/charmbracelet/bubbles/textinput"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
)

/*define styles*/
var (
	focusedStyle        = lipgloss.NewStyle().Foreground(lipgloss.Color("205"))
	blurredStyle        = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
	cursorStyle         = focusedStyle
	noStyle             = lipgloss.NewStyle()
	helpStyle           = blurredStyle
	cursorModeHelpStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("244"))

	// 提交按钮
	focusedButton = focusedStyle.Render("[ 提交 ]")
	blurredButton = fmt.Sprintf("[ %s ]", blurredStyle.Render("提交"))
)

// 核心tui逻辑， todo: 优化
func initialModel(cfg *reuse.SiteConfig, editIdx *int) *SaveModel {
	var lbls []string
	lbls = append(lbls, "ftp站点名称", "类型", "主机地址", "端口", "账号", "密码", "确认密码")
	m := &SaveModel{
		labels:  lbls,
		inputs:  make([]textinput.Model, len(lbls)),
		editIdx: editIdx,
		cfg:     *cfg,
	}

	var t textinput.Model
	for i := range m.inputs {
		t = textinput.New()
		t.Cursor.Style = cursorStyle
		t.Width = 100

		switch i {
		case 0:
			t.Placeholder = "站点名称"
			t.Focus()
			t.PromptStyle = focusedStyle
			t.TextStyle = focusedStyle
			t.SetValue(cfg.Name)
		case 1:
			t.Placeholder = "类型，FTP"
			t.SetValue(cfg.Type)
		case 2:
			t.Placeholder = "Host, 例如：127.0.0.1"
			t.SetValue(cfg.Host)
		case 3:
			t.Placeholder = "端口，默认21"
			t.SetValue(cfg.Port)
		case 4:
			t.Placeholder = "账号，必填"
			t.SetValue(cfg.Account)
		case 5:
			t.Placeholder = "密码，必填"
			t.EchoMode = textinput.EchoPassword
			t.EchoCharacter = '•'
			t.SetValue(cfg.Password)
		case 6:
			t.Placeholder = "确认密码，必填"
			t.EchoMode = textinput.EchoPassword
			t.EchoCharacter = '•'
			t.SetValue(cfg.Password)
		}

		m.inputs[i] = t
	}

	return m
}

// 对自定义Model实现Init接口
func (m *SaveModel) Init() tea.Cmd {
	return textinput.Blink
}

// 用户输入，更新View和处理逻辑
func (m *SaveModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {
		case "ctrl+c", "esc":
			return m, tea.Quit

		// Change cursor mode
		case "ctrl+r":
			m.cursorMode++
			if m.cursorMode > cursor.CursorHide {
				m.cursorMode = cursor.CursorBlink
			}
			cmds := make([]tea.Cmd, len(m.inputs))
			for i := range m.inputs {
				cmds[i] = m.inputs[i].Cursor.SetMode(m.cursorMode)
			}
			return m, tea.Batch(cmds...)

		// Set focus to next input
		case "tab", "shift+tab", "enter", "up", "down":
			s := msg.String()

			// 确认提交按钮
			if s == "enter" && m.focusIndex == len(m.inputs) {
				m.updateData()
				if m.cfg.Name == "" {
					m.err = fmt.Errorf("站点名称不能为空")
					return m, nil
				}
				if m.cfg.Host == "" {
					m.err = fmt.Errorf("主机地址不能为空")
					return m, nil
				}
				if m.cfg.Account == "" {
					m.err = fmt.Errorf("站点账号不能为空")
					return m, nil
				}
				if m.cfg.Password == "" {
					m.err = fmt.Errorf("站点密码不能为空")
					return m, nil
				}
				if m.cfg.Password != m.inputs[6].Value() {
					m.err = fmt.Errorf("两次输入的密码不一致")
					return m, nil
				}
				if m.editIdx == nil {
					if err := createImpl(&m.cfg); err != nil {
						m.err = err
						return m, nil
					}
				} else {
					if err := editImpl(&m.cfg, m.editIdx); err != nil {
						m.err = err
						return m, nil
					}
				}
				if m.err != nil {
					// draw error with bubbletea
					return m, nil
				}
				m.submitted = true
				return m, tea.Quit
			}

			// Cycle indexes
			if s == "up" || s == "shift+tab" {
				m.focusIndex--
			} else {
				m.focusIndex++
			}

			if m.focusIndex > len(m.inputs) {
				m.focusIndex = 0
			} else if m.focusIndex < 0 {
				m.focusIndex = len(m.inputs)
			}

			cmds := make([]tea.Cmd, len(m.inputs))
			for i := 0; i <= len(m.inputs)-1; i++ {
				if i == m.focusIndex {
					// Set focused state
					cmds[i] = m.inputs[i].Focus()
					m.inputs[i].PromptStyle = focusedStyle
					m.inputs[i].TextStyle = focusedStyle
					continue
				}
				// Remove focused state
				m.inputs[i].Blur()
				m.inputs[i].PromptStyle = noStyle
				m.inputs[i].TextStyle = noStyle
			}

			return m, tea.Batch(cmds...)
		}
	}

	// Handle character input and blinking
	cmd := m.updateInputs(msg)

	return m, cmd
}

// 绘画tui程序信息
func (m *SaveModel) View() string {
	var b strings.Builder

	if m.submitted {
		b.WriteString("提交成功\n")
		return b.String()
	}

	// 显示错误信息（如果有）
	if m.err != nil {
		// 用红色显示错误（lipgloss.Color("9") 是红色）
		errStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("9"))
		b.WriteString(errStyle.Render("错误: " + m.err.Error() + "\n\n"))
	}

	for i := range m.inputs {
		// 绘画
		b.WriteString(m.labels[i] + m.inputs[i].View())
		if i < len(m.inputs)-1 {
			b.WriteRune('\n')
		}
	}

	button := &blurredButton
	if m.focusIndex == len(m.inputs) {
		button = &focusedButton
	}
	_, err := fmt.Fprintf(&b, "\n\n%s\n\n", *button)
	if err != nil {
		log.Println("error: draw config View error, ", err)
		return ""
	}

	b.WriteString(helpStyle.Render("cursor mode is "))
	b.WriteString(cursorModeHelpStyle.Render(m.cursorMode.String()))
	b.WriteString(helpStyle.Render(" (ctrl+r to change style)"))

	return b.String()
}

func (m *SaveModel) updateInputs(msg tea.Msg) tea.Cmd {
	cmds := make([]tea.Cmd, len(m.inputs))

	for i := range m.inputs {
		m.inputs[i], cmds[i] = m.inputs[i].Update(msg)
	}

	return tea.Batch(cmds...)
}

// 更新ui输入数据
func (m *SaveModel) updateData() {
	m.cfg.Name = m.inputs[0].Value()
	if m.inputs[1].Value() == "" {
		m.cfg.Type = "ftp"
	} else {
		m.cfg.Type = m.inputs[1].Value()
	}

	m.cfg.Host = m.inputs[2].Value()
	if m.inputs[3].Value() == "" {
		m.cfg.Port = "21"
	} else {
		m.cfg.Port = m.inputs[3].Value()
	}

	m.cfg.Account = m.inputs[4].Value()
	m.cfg.Password = m.inputs[5].Value()
}
